package com.ithome.controller;

import com.aliyuncs.utils.StringUtils;
import com.ithome.mapper.UserMapper;
import com.ithome.pojo.User;
import com.ithome.service.SendAliSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author sandu
 * @create 2020-06-09 23:19
 */
@RestController
@CrossOrigin
public class SmsApiController {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private SendAliSms sendAliSms;

	@Autowired
	private RedisTemplate<String,String> redisTemplate;

	@RequestMapping("/send/phone")
	public Object sendCode(HttpServletRequest request,Model model){
		String phone = request.getParameter("phone");

		String code = redisTemplate.opsForValue().get(phone);
		if (!StringUtils.isEmpty(code)){
			return phone + ":" + code + "已存在，还未过期";
		}

		//生成验证码并存储到redis中
		code = UUID.randomUUID().toString().substring(0,4);
		HashMap<String,Object> param = new HashMap<>();
		param.put("code",code);

		boolean isSend = sendAliSms.send(phone, "SMS_192785005", param);

		if (isSend){
			redisTemplate.opsForValue().set(phone,code,48, TimeUnit.HOURS);
			model.addAttribute("regis-msg","请查看短信");
//			return phone + ":" +" 验证码为："+ code + "发送成功！";
			return null;
		}else {

			return "发送失败！";
		}

	}

	@RequestMapping("/register")
	public String registerBtn(HttpServletRequest request, Model model){

		String phone = request.getParameter("phone");
		String txtFpCode = request.getParameter("txtFpCode");

		User user = new User();
		user.setUid(1);
//		user.setUName(uname);
//		user.setUPassword(uPassword);
		user.setUPhone(phone);

		String redisValue = redisTemplate.opsForValue().get(phone);

		if (txtFpCode == null || txtFpCode == ""){
			model.addAttribute("register-msg","验证码不能为空");
//			return "验证码不能为空";
		}else if(txtFpCode.length()!=4){
			model.addAttribute("register-msg","请输入您手机收到的4位验证码");
//			return "请输入您手机收到的4位验证码";
		}else if(redisValue.equals(txtFpCode)){
			model.addAttribute("register-msg","您已注册成功");
			userMapper.insert(user);
//			return "您已注册成功";
		}
		return null;
	}


}
